import { RollifyConfigure } from '../typing'
import { isFunction, isObject, isString } from 'node-aux'
import { PreRenderedAsset } from 'rollup'

export const generateCssFile = (cssFileName?: string | ((name: string) => string)) => {
    return (chunInfo: PreRenderedAsset): string => {
        const { type, name } = chunInfo
        if (type === 'asset' && /\.css$/.test(name || '')) {
            if (isString(cssFileName)) {
                return cssFileName
            }
            if (isFunction(cssFileName) && name) {
                return cssFileName(name) as string
            }
            return '[name][extname]'
        }
        return '[name][extname]'
    }
}

export const outputConfigure = function <T extends RollifyConfigure>(userConfig: T) {
    const { output, scssModule } = userConfig
    if (!output) {
        return
    }
    const { filename = 'index.css' } = { ...scssModule }
    const { formats, assetFileNames, ...restOptions } = output
    let copyAssetFileNames = assetFileNames
    return {
        name: 'output',
        configure: () => {
            if (scssModule && filename && !assetFileNames) {
                copyAssetFileNames = generateCssFile(filename)
            }
            if (Array.isArray(formats) && formats.length) {
                return formats.map((config) => {
                    if (isString(config)) {
                        return {
                            format: config,
                            assetFileNames: copyAssetFileNames,
                            ...restOptions
                        }
                    }
                    if (isObject(config)) {
                        return {
                            ...config,
                            assetFileNames: copyAssetFileNames,
                            ...restOptions
                        }
                    }
                })
            }
            if (isString(formats)) {
                return { ...restOptions, formats: formats }
            }

            return { assetFileNames: copyAssetFileNames, ...restOptions }
        }
    }
}
